﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Tls.Crypto;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Device;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ProTrack.Api.Helper;
using ProTrack.Report;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 设备台账服务接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class MachineryController : ControllerBase
    {
        public MachineryController(IMachineryServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }
        private IMachineryServices Services { get; }
        private LogHelper LogHelper { get; }

        /// <summary>
        /// 获取所有设备
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("设备-获取所有", ex);
                /*status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备-获取所有", ex, HttpContext);*/
            }

            return Ok(status);
        }
        /// <summary>
        /// 根据页码，页大小，设备所属分类名称，设备编码，设备名称，设备状态获取设备信息方法
        /// </summary>
        /// <param name="PageIndex">页码</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="MachineryTypeName">设备所属分类名称</param>
        /// <param name="MachineryCode">设备编码</param>
        /// <param name="MachineryName">设备名称</param>
        /// <param name="Status">设备状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string MachineryTypeName, [FromQuery] string MachineryCode, [FromQuery] string MachineryName, [FromQuery] string Status, [FromQuery] int MachineryTypeId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAsync(PageIndex, PageSize, MachineryTypeName ?? "", MachineryCode ?? "", MachineryName ?? "", Status ?? "", MachineryTypeId);
                status.Data = list;
                status.Count = await Services.GetCountAsync(MachineryTypeName, MachineryCode, MachineryName, Status, MachineryTypeId);
            }
            catch (Exception ex)
            {
                return await Error("设备-分页获取", ex);
            }

            return Ok(status);
        }
        /// <summary>
        /// 新增设备
        /// </summary>
        /// <param name="model">设备模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] Machinery model)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                model.Creator = HttpContext.User.Identity.Name;

                var isSuccess = await Services.AddAsync(model);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("设备-新增", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 修改设备
        /// </summary>
        /// <param name="model">设备模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] Machinery model)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = HttpContext.User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model);
                if (isSuccess)
                {
                    status.Msg = "修改成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("设备-修改", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 批量删除设备
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("设备-批量删除", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();

            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("设备-删除", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {
                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[]{
                new ReportDomain{Title="序号",Fileld="No"},
                new ReportDomain{Title="设备编码",Fileld="MachineryCode"},
                new ReportDomain{Title="设备名称",Fileld="MachineryName"},
                new ReportDomain{Title="所属分类",Fileld="MachineryTypeName"},
                new ReportDomain{Title="所属车间",Fileld="WorkshopName"},
                new ReportDomain{Title="设备状态",Fileld="Status"},
                new ReportDomain{Title="位置",Fileld="Location"},
                new ReportDomain{Title="创建日期",Fileld="CreateTime"},
                new ReportDomain{Title="购买日期",Fileld="PurchasingTime"},
                new ReportDomain{Title="规格型号",Fileld="MachinerySpec"},
                new ReportDomain{Title="产能",Fileld="Capacity"},
                new ReportDomain{Title="备注",Fileld="Remark"}
            };
                var fileArray = BaseReport.Export(list, "设备台账信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "设备台账信息.xls");
            }
            catch(Exception ex)
            {
                await LogHelper.WriteErrorLog("设备台账-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }
            
        }
        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="ExString"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        private async Task<IActionResult> Error(string ExString, Exception ex)
        {
            var status = BaseStatus.CreateInstance();
            status.Code = -1;
            status.Msg = "服务器异常，请稍后重试！";
            //写日志
            await LogHelper.WriteErrorLog(ExString, ex, HttpContext);
            return new ObjectResult(status) { StatusCode = StatusCodes.Status500InternalServerError };
        }

    }
}
